<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="任务名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter="handleQuery"
          class="!w-260px"
        />
      </el-form-item>
      <el-form-item label="任务类型" prop="type">
        <el-select
          clearable
          v-model="queryParams.type"
          placeholder="请选择任务类型"
          class="!w-260px"
        >
          <el-option v-for="(v, k) in CallTypeEnumMap" :key="k" :label="v" :value="k" />
        </el-select>
      </el-form-item>
      <el-form-item label="任务状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择任务状态"
          clearable
          class="!w-260px"
        >
          <el-option v-for="(v, k) in CallTaskstatusEnumMap" :key="k" :label="v" :value="k" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" />
          重置
        </el-button>
        <el-button type="primary" @click="openForm('create')" v-hasPermi="['call:task:create']">
          <Icon icon="ep:plus" class="mr-5px" />
          新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['call:task:export']"
        >
          <Icon icon="ep:download" class="mr-5px" />
          导出
        </el-button>
        <el-button type="primary" @click="showCallPage">
          <Icon icon="ep:tickets" class="mr-5px" />
          呼叫名单</el-button
        >
        <el-button type="primary" @click="showVoiceFile">
          <Icon icon="ep:microphone" class="mr-5px" />
          语音文件管理</el-button
        >
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true" border>
      <el-table-column label="任务名称" align="center" prop="name" width="150px">
        <template #default="scope">
          <el-link :underline="false" type="primary" @click="goDetail(scope.row.id)">{{
            scope.row.name
          }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="任务类型" align="center" prop="type" width="100px">
        <template #default="scope">
          <span>{{ CallTypeEnumMap[scope.row.type] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="并发模式" align="left" width="200px">
        <template #default="scope">
          <div class="flex items-center">
            <div>
              <div>并发模式：{{ concurrOption[scope.row.concurrenceMode] }}</div>
              <div>并发倍率：{{ scope.row.multiplier }}</div>
            </div>
            <el-icon
              :size="18"
              style="margin-left: 20px; cursor: pointer"
              @click="editCurr(scope.row)"
            >
              <Edit />
            </el-icon>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="号码量" align="center" prop="numberCount" width="70px" />
      <el-table-column label="已呼数量" align="center" prop="callCount" width="100px" />
      <el-table-column label="任务状态" align="center" prop="status" width="100px">
        <template #default="scope">
          <span>{{ CallTaskstatusEnumMap[scope.row.status] }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="开始时间"
        align="center"
        prop="startTime"
        :formatter="dateFormatter"
        width="170px"
      />
      <el-table-column
        label="结束时间"
        align="center"
        prop="endTime"
        :formatter="dateFormatter"
        width="170px"
      />

      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="170px"
      />
      <el-table-column align="center" prop="prop" label="执行日期1">
        <template #default="scope">
          {{
            weekOption
              .filter((option) => scope.row.weekday1?.includes(option.value))
              .map((item) => item.label)
              .join(',')
          }}
          <br />
          {{ scope.row.startTime1 }}
          <br />
          {{ scope.row.endTime1 }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="prop" label="执行日期2">
        <template #default="scope">
          {{
            weekOption
              .filter((option) => scope.row.weekday2?.includes(option.value))
              .map((item) => item.label)
              .join(',')
          }}
          <br />
          {{ scope.row.startTime2 }}
          <br />
          {{ scope.row.endTime2 }}
        </template>
      </el-table-column>
      <el-table-column align="center" prop="prop" label="执行日期3">
        <template #default="scope">
          {{
            weekOption
              .filter((option) => scope.row.weekday3?.includes(option.value))
              .map((item) => item.label)
              .join(',')
          }}
          <br />
          {{ scope.row.startTime3 }}
          <br />
          {{ scope.row.endTime3 }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="280px" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="controlTask(scope.row)"
            v-hasPermi="['call:task:update']"
          >
            {{ scope.row.status == 9 ? '停止' : '启动' }}
          </el-button>
          <el-button type="primary" link @click="goDetail(scope.row.id)">详情</el-button>
          <el-button type="success" link @click="appendPhone(scope.row)">追加</el-button>
          <el-button type="success" link @click="taskHeavy(scope.row.id)">任务重呼</el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['call:task:delete']"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <TaskForm ref="formRef" @success="getList" />
  <!-- 呼叫名单 -->
  <CallList ref="callRefs" />
  <!-- 语音文件管理 -->
  <VoiceFileManagement ref="voiceRefs" />
  <!-- 追加外呼号码 -->
  <AppendTask ref="appendRefs" @success="getList" />
  <!-- 编辑并发 -->
  <Concurrent ref="concurrRefs" @success="getList" />
  <!-- 任务重呼 -->
  <HeavyTask ref="heavyRefs" @success="getList" />
</template>

<script setup lang="ts">
import { Edit } from '@element-plus/icons-vue'
import download from '@/utils/download'
import * as TaskApi from '@/api/call/task'
import { dateFormatter } from '@/utils/formatTime'
import TaskForm from './TaskForm.vue'
import CallList from './callList/index.vue'
import VoiceFileManagement from './voiceFile/index.vue'
import AppendTask from './append.vue'
import Concurrent from './concurr.vue'
import HeavyTask from './heavyTask/index.vue'

defineOptions({ name: 'CallTask' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: null,
  type: null,
  status: null,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const CallTypeEnumMap = {
  1: '普通群呼',
  2: '语音按键业务',
  3: '语音转坐席业务'
}
const concurrOption = {
  0: '智能',
  1: '固定'
}
const CallTaskstatusEnumMap = {
  0: '执行完毕',
  1: '等待执行',
  2: '执行错误',
  3: '暂停',
  4: '手动停止',
  9: '执行中'
}
const weekOption = [
  {
    label: '星期一',
    value: '1'
  },
  {
    label: '星期二',
    value: '2'
  },
  {
    label: '星期三',
    value: '3'
  },
  {
    label: '星期四',
    value: '4'
  },
  {
    label: '星期五',
    value: '5'
  },
  {
    label: '星期六',
    value: '6'
  },
  {
    label: '星期日',
    value: '0'
  }
]
const concurrRefs = ref(null)
/*编辑并发模式*/
const editCurr = (item) => {
  concurrRefs.value.open(item)
}
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await TaskApi.getTaskPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 启动/停止操作 */
const controlTask = async (row) => {
  const data = {
    id: row.id,
    action: row.status == 9 ? 'stop' : 'start'
  }
  await TaskApi.controlTask(data)
  if (data.action == 'start') {
    message.success('操作成功，请通知坐席进入呼叫中心并登录话机')
  } else {
    message.success('操作成功')
  }

  // 刷新列表
  await getList()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await TaskApi.deleteTask(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await TaskApi.exportTask(queryParams)
    download.excel(data, '外呼任务.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
const { push } = useRouter()
/** 打开详情 */
const goDetail = (id) => {
  push('/task/taskDetail?id=' + id)
}
const appendRefs = ref(null)
/*追加*/
const appendPhone = (item) => {
  appendRefs.value.open(item.taskId)
}
const heavyRefs = ref(null)
/*任务重呼*/
const taskHeavy = (id) => {
  heavyRefs.value.open(id)
}
const callRefs = ref(null)
/*显示呼叫名单*/
const showCallPage = () => {
  callRefs.value.open()
}
/*显示语音文件*/
const voiceRefs = ref(null)
const showVoiceFile = () => {
  voiceRefs.value.open()
}
/** 初始化 **/
onMounted(() => {
  getList()
})
</script>
